<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\dispatch\TaskRequest;
use App\Models\base\WarehouseModel;
use App\Models\dispatch\CarModel;
use App\Models\dispatch\DriverModel;
use App\Models\dispatch\UnloadModel;
use App\Models\DispatchCostModel;
use App\Models\DispatchLoadListModel;
use App\Models\DispatchTaskDriverModel;
use App\Models\DispatchTaskLoadModel;
use App\Models\DispatchTaskLocationModel;
use App\Models\DispatchTaskModel;
use App\Models\DispatchTaskRecordModel;
use App\Models\DispatchTaskUnloadModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Task extends Controller
{
    public function list(Request $request) {
        $auth = $request->get('auth');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $status = $request->input('status', '');
        $driver_id = $auth->id;

        $driver = DriverModel::query()->where('id', $driver_id)->first();
        $driver_type =  $driver->type;

        $query = DispatchTaskModel::query()
            ->with([
                'loads', 'unloads', 'driver', 'hk_driver', 'car', 'type'
            ]);

        if($driver_type == 1){
            $query->where('hk_driver_id', $driver_id)->where('status', $status);
        }

        if($driver_type == 2){
            $query->where('driver_id', $driver_id)->where('status', $status);
        }


        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            //车牌号
            $car_number = $item->car ? $item->car->car_number : '';

            //装车地
            $load_warehouse_ids = $item->loads->map(function ($item2) {
                return $item2->warehouse_id;
            });

            $load_warehouse_name = WarehouseModel::whereIn('id', $load_warehouse_ids)->pluck('name')->toArray();

            //卸货地
            $unload_warehouse_ids = $item->unloads->map(function ($item2) {
                return $item2->warehouse_id;
            });

            $unload_warehouse_name = UnloadModel::whereIn('id', $unload_warehouse_ids)->pluck('name')->toArray();


            
            return [
                'id' => $item->id,
                'car_type' => $item->type->name ?? '',
                'car_number' => $car_number,
                'load_warehouse_name' => $load_warehouse_name,
                'unload_warehouse_name' => $unload_warehouse_name,
                'created_at' => $item->load_date,
            ];
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:详情
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 17:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request) {
        $auth = $request->get('auth');
        $id = $request->input('id', 0);

        $model = DispatchTaskModel::query()
            ->with([
                'loads', 'unloads', 'car', 'feng', 'load_list', 'driver', 'hk_driver', 'type'
            ])->find($id);

        if (!$model) {
            return $this->error('数据不存在');
        }

        //车牌号
        $car_number = $model->car->car_number ?? '';

        //装车地
        $load_warehouse_ids = $model->loads->map(function ($item2) {
            return $item2->warehouse_id;
        });

        $load_warehouse_name = WarehouseModel::whereIn('id', $load_warehouse_ids)->select('id', 'name', 'address', 'mobile')->get();

        //卸货地
        $unload_warehouse_ids = $model->unloads->map(function ($item2) {
            return $item2->warehouse_id;
        });

        $unload_warehouse_name = UnloadModel::whereIn('id', $unload_warehouse_ids)->select('id', 'name', 'address', 'mobile')->get();


        $return['base_info'] = [
            'car_type' => $item->type->name ?? '',
            'car_number' => $car_number,
            'type' => $model->type->name ?? '',
            'weight' => $model->load_list ? $model->load_list->sum('weight') : 0,
            'big_pkgs' => $model->load_list ? $model->load_list->sum('big_pkgs') : 0,
            'load_warehouse_name' => $load_warehouse_name,
            'unload_warehouse_name' => $unload_warehouse_name,
            'feng_name' => $model->feng->name ?? '',
            'created_at' => $model->load_date,
        ];

        $driver_info = [];
        if($model->driver){
            $driver_info[] = [
                'name' => $model->driver->name,
                'mobile' => $model->driver->mobile,
                'type' => DriverModel::TYPE[$model->driver->type] ?? ''
            ];
        }

        if($model->hk_driver){
            $driver_info[] = [
                'name' => $model->hk_driver->name,
                'mobile' => $model->hk_driver->mobile,
                'type' => DriverModel::TYPE[$model->hk_driver->type] ?? ''
            ];
        }

        $return['driver_info'] = $driver_info;


        $transport_info = [];

        $record = DispatchTaskRecordModel::with(['warehouse', 'unload', 'driver'])->where('task_id', $id)->orderBy('id', 'asc')->get();

        foreach ($record as $item) {
            $driver_name = $item->driver->name ?? '';
            $transport_info[] = [
                'time' => $item->time,
                'desc' => $item->desc . '【' . $driver_name . '】',
            ];
        }

        $return['transport_info'] = $transport_info;

        $driver = DispatchTaskDriverModel::where('task_id', $id)->where('driver_id', $auth->id)->first();

        $return['button'] = [];
        if($driver && !$driver->end && $driver->is_start){

            $type = ''; $warehouse = [];

            //装车点
            if(($driver->status_type == 1 || $driver->status_type == 3) && ($driver->driver_status == 1 || $driver->driver_status == 2)){
                $not_arrive = $model->loads->where('is_arrive', 0);
                if(count($not_arrive) > 0){
                    $type = 'load';
                    $warehouse = $not_arrive->map(function ($item) {
                        return [
                            'id' => $item->warehouse_id,
                            'name' => WarehouseModel::find($item->warehouse_id)->name ??  '',
                        ];
                    });
                    $warehouse = array_values($warehouse->toArray());
//                    $warehouse_id = $not_arrive->warehouse_id;
                    $driver_status = 2;
//                    $load_warehouse = WarehouseModel::find($not_arrive->warehouse_id);
//                    $load_name = $load_warehouse->name ?? '';
//                    $status_name = '到仓【'.$load_name.'】';
                }else{
                    $driver_status = $driver->driver_status + 1;
                }
            }else if(($driver->status_type == 2 && ($driver->driver_status == 2 || $driver->driver_status == 3)) || ($driver->status_type == 3 && ($driver->driver_status == 6 || $driver->driver_status == 7))){//卸货点
                $not_arrive = $model->unloads->where('is_arrive', 0)->where('is_arrive', 0);
                if(count($not_arrive) > 0){
                    $type = 'unload';
                    $warehouse = $not_arrive->map(function ($item) {
                        return [
                            'id' => $item->warehouse_id,
                            'name' => UnloadModel::find($item->warehouse_id)->name ??  '',
                        ];
                    });
                    $warehouse = array_values($warehouse->toArray());
                    if($driver->status_type == 2) {
                        $driver_status = 3;
                    }
                    if($driver->status_type == 3) {
                        $driver_status = 7;
                    }
//                    $warehouse_id = $not_arrive->warehouse_id;
//                    $driver_status = $driver->driver_status;
//                    $unload_warehouse = UnloadModel::find($not_arrive->warehouse_id);
//                    $unload_name = $unload_warehouse->name ?? '';
//                    $status_name = '到达卸货点【'.$unload_name.'】';
                }else{
                    $driver_status = $driver->driver_status + 1;
                }

            }else{
                $driver_status = $driver->driver_status + 1;
            }


            $status_name = DispatchTaskDriverModel::DRIVER_STATUS[$driver->status_type][$driver_status] ?? '下一步';


            $return['button'] = [
                'name' => $status_name,
                'status' => $driver_status,
                'type' => $type,
                'warehouse' => $warehouse,
            ];
        }


        if($model->is_read == 0){
            $model->is_read = 1;
            $model->save();
        }

        return $this->success($return);

    }

    //确认状态
    public function confirm_status(Request $request)
    {
        $auth = $request->get('auth');
        $id = $request->input('id', 0);
        $status  = $request->input('status', 0);
        $warehouse_id = $request->input('warehouse_id', 0);
        $warehouse_name = $request->input('warehouse_name', '');
        $type = $request->input('type', '');
        $latitude = $request->input('latitude',  '');
        $longitude = $request->input('longitude',  '');

        $model = DispatchTaskModel::find($id);

        if (!$model) {
            return $this->error('任务不存在');
        }

        DB::beginTransaction();
        try {

        if($model->status == DispatchTaskModel::STATUS_WAIT){
            $model->status = DispatchTaskModel::STATUS_TRANSPORTING;
            $model->save();
        }

        if($type == 'load'){
            DispatchTaskLoadModel::where('dispatch_task_id', $id)->where('warehouse_id', $warehouse_id)->update(
                [
                    'is_arrive' => 1
                ]
            );
        }

        if($type == 'unload'){
            DispatchTaskUnloadModel::where('dispatch_task_id', $id)->where('warehouse_id', $warehouse_id)->update(
                [
                    'is_arrive' => 1
                ]
            );
        }

        $driver  = DispatchTaskDriverModel::where('task_id', $id)->where('driver_id', $auth->id)->first();

        if(!$driver){
            return $this->error('任务司机不存在');
        }

        $driver->driver_status = $status;

        if(!isset(DispatchTaskDriverModel::DRIVER_STATUS[$driver->status_type][$status + 1])){
            if(($driver->status_type == 2 || $status == 3) || ($driver->status_type == 3 || $status == 7)){
                $not_arrive = $model->unloads->where('is_arrive', 0)->first();
                if(!$not_arrive){
                    $driver->end = 1;
                }
            }else{
                $driver->end = 1;
            }

        }

        $driver->save();

        if($driver->end){
            $find = DispatchTaskDriverModel::where('task_id', $id)->where('end', 0)->first();
            if(!$find){
                $model->status = DispatchTaskModel::STATUS_FINISHED;
                $model->save();
            }else{
                if(!$find->is_start){
                    $find->is_start = 1;
                    $find->save();
                }
            }

        }

        $desc = DispatchTaskDriverModel::DRIVER_STATUS[$driver->status_type][$status] ?? '';
        if($warehouse_name && $desc){
            $desc .= '【'.$warehouse_name.'】';
        }

        if($latitude && $longitude){
            $location = $this->get_location_from_coordinates($latitude, $longitude);
        }else{
            $location = '';
        }

        $record = new DispatchTaskRecordModel();
        $record->task_id = $id;
        $record->driver_id = $auth->id;
        $record->desc = $desc;
        $record->latitude = $latitude;
        $record->longitude = $longitude;
        $record->location = $location;
        $record->time = date('Y-m-d H:i:s');
        $record->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:仓库位置
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 17:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouse_location(Request $request)
    {
        $id = $request->input('id', 0);

        $warehouse = WarehouseModel::find($id);

        if(!$warehouse){
            return $this->error('数据不存在');
        }

        $return = [
            'name' => $warehouse->name,
            'city' => $warehouse->city,
            'address' => $warehouse->address,
            'mobile' => $warehouse->mobile,
        ];
        return $this->success($return);
    }

    /**
     * Notes:开始运输
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 17:43
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(Request $request){
        $auth = $request->get('auth');
        $id = $request->input('id', 0);

        $model = DispatchTaskModel::find($id);

        if (!$model) {
            return $this->error('数据不存在');
        }

        DB::beginTransaction();
        try {
            $model->status = 2;
            $model->save();

            $driver = DispatchTaskDriverModel::where('task_id', $id)->where('driver_id', $auth->id)->first();
            if($driver){
                $driver->status = 2;
                $driver->save();
            }

            $record = new DispatchTaskRecordModel();
            $record->task_id = $id;
            $record->driver_id = $auth->id;
            $record->type = 'start';
            $record->time = date('Y-m-d H:i:s');
            $record->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }


        return $this->success();
    }

    /**
     * Notes:经停点信息
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 18:16
     * @return \Illuminate\Http\JsonResponse
     */
    public function warehouse(Request $request)
    {
        $id = $request->input('id', 0);
        $model = DispatchTaskModel::find($id);

        if (!$model) {
            return $this->error('数据不存在');
        }

        $pass_info = WarehouseModel::find($model->pass_warehouse_id);

        $return = [
            'id' => $pass_info->id ?? '',
            'name' => $pass_warehouse_name ?? '',
        ];


        return $this->success($return);
    }

    /**
     * Notes:到达经停点
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 18:16
     * @return \Illuminate\Http\JsonResponse
     */
    public function pass(Request $request){
        $auth = $request->get('auth');
        $id = $request->input('id', 0);
        $warehouse_id = $request->input('warehouse_id', 0);

        $task = DispatchTaskModel::find($id);

        if (!$task) {
            return $this->error('数据不存在');
        }

        $model = new DispatchTaskRecordModel();
        $model->driver_id = $auth->id;
        $model->task_id = $id;
        $model->warehouse_id = $warehouse_id;
        $model->type = 'pass';
        $model->time = date('Y-m-d H:i:s');
        $model->save();

        return $this->success();
    }

    /**
     * Notes:到达装车点
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 18:16
     * @return \Illuminate\Http\JsonResponse
     */
    public function arrive_load(Request $request){
        $auth = $request->get('auth');
        $id = $request->input('id', 0);
        $warehouse_id = $request->input('warehouse_id', 0);

        $task = DispatchTaskModel::find($id);

        if (!$task) {
            return $this->error('数据不存在');
        }

        $model = new DispatchTaskRecordModel();
        $model->driver_id = $auth->id;
        $model->task_id = $id;
        $model->warehouse_id = $warehouse_id;
        $model->type = 'load';
        $model->time = date('Y-m-d H:i:s');
        $model->save();

        return $this->success();
    }

    /**
     * Notes:到达卸货点
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 18:16
     * @return \Illuminate\Http\JsonResponse
     */
    public function arrive_unload(Request $request){
        $auth = $request->get('auth');
        $id = $request->input('id', 0);
        $warehouse_id = $request->input('warehouse_id', 0);

        $task = DispatchTaskModel::find($id);

        if (!$task) {
            return $this->error('数据不存在');
        }

        $model = new DispatchTaskRecordModel();
        $model->driver_id = $auth->id;
        $model->task_id = $id;
        $model->warehouse_id = $warehouse_id;
        $model->type = 'unload';
        $model->time = date('Y-m-d H:i:s');
        $model->save();

        return $this->success();
    }

    /**
     * Notes:查看货物
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 19:04
     * @return \Illuminate\Http\JsonResponse
     */
    public function load_list(Request $request){
        $id = $request->input('id', 0);

        $list = DispatchLoadListModel::with('order')->where('dispatch_task_id', $id)->get();

        $return = $list->map(function($item){
            $res = [
                'id' => $item->id,
                'order_id' => $item->order_id,
                'order_sn' => $item->order->sn ?? '',
                'big_pkgs' => $item->big_pkgs ?? 0,
                'weight' => $item->weight ?? 0,
            ];
            return $res;
        });
        return $this->success($return);
    }

    /**
     * Notes:完成
     * User: xiangzi
     * Date: 2024/10/9
     * Time: 19:10
     * @return \Illuminate\Http\JsonResponse
     */
    public function complete(Request $request){
        $auth = $request->get('auth');
        $id = $request->input('id', 0);

        $model = DispatchTaskModel::find($id);

        if (!$model) {
            return $this->error('数据不存在');
        }

        DB::beginTransaction();
        try {

            $model->status = 3;
            $model->complete_time = date('Y-m-d H:i:s');
            $model->save();

//            $driver = DispatchTaskDriverModel::where('task_id', $id)->where('driver_id', $auth->id)->first();
            $driver = DispatchTaskDriverModel::where('task_id', $id)->first();
            if($driver){
                DispatchTaskDriverModel::where('task_id', $id)->update(['status' => 3]);
//                $driver->status = 3;
//                $driver->save();
            }

            $record = new DispatchTaskRecordModel();
            $record->task_id = $id;
            $record->driver_id = $auth->id;
            $record->warehouse_id = $model->unload_warehouse_id;
            $record->type = 'end';
            $record->time = date('Y-m-d H:i:s');
            $record->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }


    public function location(Request $request)
    {
        $auth = $request->get('auth');
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');
        $task_id = $request->input('task_id', 0);

        $task = DispatchTaskModel::find($task_id);

        if(!$task){
            return $this->error('任务不存在');
        }

        $location = $this->get_location_from_coordinates($latitude, $longitude);

        $model = new DispatchTaskLocationModel();
        $model->driver_id = $auth->id;
        $model->task_id = $task_id;
        $model->lat = $latitude;
        $model->lng = $longitude;
        $model->location = $location;
        $model->save();

        return $this->success($location);
    }

    /**
     * Notes:根据经纬度获取地址信息
     * User: xiangzi
     * Date: 2024/10/18
     * Time: 上午11:49
     * @return mixed|string
     */
    public function get_location_from_coordinates($latitude, $longitude) {

        $apiKey = 'DbAZUAV0IbWj41C8xxjXXRGskACvVWS7';
        // 构建请求URL
        $url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak={$apiKey}&output=json&coordtype=wgs84ll&location={$latitude},{$longitude}";

        // 初始化cURL会话
        $ch = curl_init();

        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // 执行cURL请求
        $response = curl_exec($ch);

        // 检查是否有错误发生
        if (curl_errno($ch)) {
//            echo 'Error:' . curl_error($ch);
            return '';
        }

        // 关闭cURL会话
        curl_close($ch);

        // 解析JSON响应
        $result = json_decode($response, true);

        // 检查是否成功获取结果
        if ($result['status'] == 0) {
            // 获取结果中的地址
            $address = $result['result']['formatted_address'];
            return $address;
        } else {
            return '';
        }
    }



}
